package com.huike.game.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SideView extends RelativeLayout {

    private TextView tv_collect;
    private TextView tv_cancel;
    private int tv_collectMeasuredWidth;
    private int height;
    private int width;
    private int tv_cancelMeasuredWidth;

    public SideView(Context context) {
        this(context,null);
    }

    public SideView(Context context, AttributeSet attrs) {
        this(context, attrs,-1);
    }

    public SideView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        tv_collect = (TextView) getChildAt(0);
        tv_cancel = (TextView) getChildAt(1);


    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        tv_collectMeasuredWidth = tv_collect.getMeasuredWidth();
        tv_cancelMeasuredWidth = tv_cancel.getMeasuredWidth();
        height = getMeasuredHeight();
        width = getMeasuredWidth();

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);


        tv_collect.layout(width,0,width+tv_collectMeasuredWidth,height);
        tv_cancel.layout(width+tv_collectMeasuredWidth,0,width+tv_collectMeasuredWidth+tv_cancelMeasuredWidth,height);


    }


    private float start;
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:

                 start = event.getX();

                break;
            case MotionEvent.ACTION_MOVE:

                float end = event.getX();
                float dy = end - start;


                int toScrollX = (int) (getScrollX() - dy);

                if(toScrollX < 0){
                    toScrollX = 0;
                }else if(toScrollX > tv_cancelMeasuredWidth + tv_collectMeasuredWidth ){
                    toScrollX = tv_cancelMeasuredWidth+ tv_collectMeasuredWidth;
                }

                scrollTo(toScrollX,getScrollY());

                start = event.getX();

                getParent().requestDisallowInterceptTouchEvent(true);//反拦截listView滑动事件

                break;
            case MotionEvent.ACTION_UP:

                int scrollX = getScrollX();//滑动距离

                if(scrollX <= tv_collectMeasuredWidth){
                    close();
                }else{
                    scrollTo(tv_collectMeasuredWidth + tv_cancelMeasuredWidth,getScrollY());

                }


                break;
        }

        return true;
    }

    public void close(){
        scrollTo(0,getScrollY());
    }
}
